package com.hliushi.redis.service.impl;

import com.hliushi.redis.entity.Users;
import com.hliushi.redis.mapper.UsersMapper;
import com.hliushi.redis.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
@CacheConfig(cacheNames = {"user"}) // 统一该类的所有缓存的前缀是以 "user::"为前缀
public class UsersServiceImpl implements UsersService {

    @Resource
    private UsersMapper usersMapper;

    @Override
    public int insert(Users record) {
        return usersMapper.insert(record);
    }

    @Override
    public int insertSelective(Users record) {
        return usersMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(Users record) {
        return usersMapper.updateByPrimaryKeySelective(record);
    }


    /**
     * # @Cacheable(key = "#id")是方法级别的注解, 用于将方法的结果缓存起来
     * # 下面的代码被调用时, 先从缓存中读取数据, 如果缓存没有找到数据, 在执行方法体, 最后把返回值添加到缓存中
     *
     * @param id
     * @return
     */
    @Override
    @Cacheable(key = "#id")
    public Users selectByPrimaryKey(Integer id) {
        return usersMapper.selectByPrimaryKey(id);
    }


    /**
     * # @CachePut(key = "#record.id")
     * 以上方法被调用时, 先执行方法体, 然后springcache通过返回值更新缓存, 即key = "#record.id", value=user
     *
     * @param record
     * @return
     */
    @Override
    @CachePut(key = "#record.id")
    public Users updateByPrimaryKey(Users record) {
        usersMapper.updateByPrimaryKey(record);
        return this.usersMapper.selectById(record.getId());
    }


    /**
     * # @CacheEvict(key = "#id") 是方法级别的注解, 用于删除缓存
     * 以上方法被调用是, 先执行方法体, 在通过方法参数删除缓存
     *
     * @param id
     * @return
     */
    @Override
    @CacheEvict(key = "#id")
    public int deleteByPrimaryKey(Integer id) {
        return usersMapper.deleteByPrimaryKey(id);
    }
}
